package org.happylearn.jdk.concurrent;

/**
 * 测试Object.wait().
 * @author ljh
 *
 */
public class WaitTest {
	static Object lock = new Object();
	
	static volatile int state = 1;
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread() {
			public void run() {
				synchronized (lock) {	//1.获取对象监视器
					while(state != 2) {	//2.condition in loop.
						try {
							lock.wait();	//3.调用wait，（释放监视器，等待唤醒）
							//4.重新竞争监视器
							Thread.sleep(100000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}  
					}
					//5.process self service
					
					System.out.println("ok, i relife again.");
				}
			};
			
		};
		Thread t2 = new Thread() {
			public void run() {
				synchronized (lock) {			
					System.out.println("thread2 获取到了监视器");
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					state = 2;
					lock.notify();
				}		//结束
				
			};
			
		};
		t1.start();
		t2.start();
		
		System.out.println("before join: "+t1.isAlive());
		//main线程
		t1.join();	
		System.out.println("after join: "+t1.isAlive());
		
		//main线程
		t2.join();
		
	}
}
